const db = wx.cloud.database();

const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}
const formatDate = date => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();

    return [year, month, day].map(formatNumber).join('-');
}
const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : `0${n}`
}

function saveUserAns(userAns, userInfo) {
    db.collection('userAnswers')
        .where({
            _openId: userInfo.openId
        }).get().then(res => {
        let temp = res.data;
        if (temp.length === 0) {
            //未找到此_openid, 便写入新的值
            db.collection('userAnswers').add({
                data: {
                    nickName: userInfo.nickName,
                    answer: userAns,
                    time: this.formatTime(new Date())
                }
            });
        } else {
            //若找到此_openid, 则更新
            db.collection('userAnswers')
                .where({
                    _openid: userInfo.openId
                }).update({
                data: {
                    nickName: userInfo.nickName,
                    answer: userAns,
                    time: this.formatTime(new Date())
                }
            });
        }
    })
}

module.exports = {
    formatTime,
    formatDate: formatDate
}
